<template>
	<view class="container">
		<view class="header">
			<text class="title">AI语音助手</text>
		</view>
		<view class="content">
			<!-- 录音状态显示 -->
			<view class="status-box">
				<text class="status-text">{{ recordStatus }}</text>
				<text v-if="isRecording" class="timer">{{ formatTime(recordTime) }}</text>
			</view>
			
			<!-- 录音控制按钮 -->
			<view class="control-box">
				<view class="record-btn" :class="{recording: isRecording}" @tap="toggleRecord">
					<text>{{ isRecording ? '停止' : '开始录音' }}</text>
				</view>
			</view>
		
			<!-- 录音文件操作 -->
			<view v-if="recordFilePath" class="file-box">
				<view class="file-info">
					<text>录音已保存</text>
					<text class="file-duration">时长: {{ formatTime(recordDuration) }}</text>
				</view>
				
				<view class="action-box">
					<button class="action-btn" @tap="playRecord">播放</button>
					<button class="action-btn primary" @tap="uploadRecord">上传到AI</button>
				</view>
			</view>
			
			<!-- AI分析结果 -->
			<view v-if="aiResult" class="result-box">
				<view class="result-title">
					<text>AI回复结果</text>
				</view>
				<view class="result-content">
					<text>{{ aiResult }}</text>
				</view>
			</view>
		</view>
	</view>
</template>
<script setup>
import { ref, onMounted } from 'vue';

// 录音相关状态
const isRecording = ref(false);
const recordStatus = ref('准备就绪');
const recordTime = ref(0);
const recordFilePath = ref('');
const recordDuration = ref(0);
const aiResult = ref('');
// 计时器
let timer = null;

// 录音管理器
let recorderManager = null;
// 音频播放器
let innerAudioContext = null;

// 初始化录音和播放器
onMounted(() => {
	// 初始化录音管理器
	recorderManager = uni.getRecorderManager();
	
	// 监听录音开始事件
	recorderManager.onStart(() => {
		console.log('录音开始');
		recordStatus.value = '正在录音...';
		isRecording.value = true;
		
		// 开始计时
		recordTime.value = 0;
		timer = setInterval(() => {
			recordTime.value++;
		}, 1000);
	});
	// 监听录音结束事件
	recorderManager.onStop((res) => {
		console.log('录音结束', res);
		recordStatus.value = '录音已完成';
		isRecording.value = false;
		
		// 停止计时
		clearInterval(timer);
		
		// 保存录音文件路径和时长
		recordFilePath.value = res.tempFilePath;
		console.log("当前录音位置",recordFilePath.value)
		recordDuration.value = Math.floor(res.duration / 1000); // 转换为秒
	});
	
	// 监听录音错误事件
	recorderManager.onError((res) => {
		console.error('录音错误', res);
		recordStatus.value = '录音出错: ' + res.errMsg;
		isRecording.value = false;
		clearInterval(timer);
	});
	
	// 初始化音频播放器
	innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.onError((res) => {
		console.error('播放错误', res);
		uni.showToast({
			title: '播放失败',
			icon: 'none'
		});
	});
});
// 开始/停止录音
const toggleRecord = () => {
	if (isRecording.value) {
		// 停止录音
		recorderManager.stop();
	} else {
		// 开始录音
		recorderManager.start({
			duration: 6000, //1分钟
			sampleRate: 16000, // 采样率
			numberOfChannels: 1, // 录音通道数
			encodeBitRate: 96000, // 编码码率
			format: 'mp3', // 音频格式
		});
	}
};

// 播放录音
const playRecord = () => {
	if (!recordFilePath.value) {
		uni.showToast({
			title: '没有录音文件',
			icon: 'none'
		});
		return;
	}
	innerAudioContext.src = recordFilePath.value;
	innerAudioContext.play();
	
	uni.showToast({
		title: '正在播放',
		icon: 'none'
	});
};
// 上传录音到后端
const uploadRecord = () => {
	if (!recordFilePath.value) {
		uni.showToast({
			title: '没有录音文件',
			icon: 'none'
		});
		return;
	}
	// 显示上传中
	uni.showLoading({
		title: '正在上传并分析'
	});
	// 上传文件
	uni.uploadFile({
		url: 'http://localhost:8088/UserAppLogin/updateVoice', 
		filePath: recordFilePath.value,
		name: 'file',

		// formData: {
			
		// },
		success: (uploadRes) => {
			console.log('res', uploadRes);
			uni.hideLoading();
			
			// 解析返回结果
			// try {
			// 	const result = JSON.parse(uploadRes.data);
			// 	aiResult.value = result.content || '分析完成';
			// } catch (e) {
			// 	console.error('解析结果失败', e);
			// 	aiResult.value = uploadRes.data || '分析完成，但结果格式异常';
			// }
			
			// uni.showToast({
			// 	title: '分析完成',
			// 	icon: 'success'
			// });
		},
		fail: (err) => {
			console.error('上传失败', err);
			uni.hideLoading();
			uni.showToast({
				title: '上传失败',
				icon: 'none'
			});
		}
	});
};

// 格式化时间显示 (秒 -> MM:SS)
const formatTime = (seconds) => {
	const minutes = Math.floor(seconds / 60);
	const remainingSeconds = seconds % 60;
	return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
};
</script>

<style>
.container {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 20px;
	background-color: #f8f8f8;
	height: 100vh;
}

.header {
	width: 100%;
	text-align: center;
	margin-bottom: 30px;
}

.title {
	font-size: 24px;
	font-weight: bold;
	color: #333;
}

.content {
	width: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.status-box {
	width: 100%;
	text-align: center;
	margin-bottom: 20px;
}

.status-text {
	font-size: 18px;
	color: #666;
}

.timer {
	display: block;
	font-size: 24px;
	color: #ff6b81;
	margin-top: 10px;
	font-weight: bold;
}

.control-box {
	width: 100%;
	display: flex;
	justify-content: center;
	margin-bottom: 30px;
}

.record-btn {
	width: 150px;
	height: 150px;
	border-radius: 75px;
	background-color: #ff6b81;
	display: flex;
	justify-content: center;
	align-items: center;
	color: white;
	font-size: 18px;
	font-weight: bold;
	box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
	transition: all 0.3s ease;
}

.record-btn.recording {
	background-color: #ff4757;
	transform: scale(1.1);
	animation: pulse 1.5s infinite;
}

@keyframes pulse {
	0% {
		transform: scale(1);
	}
	50% {
		transform: scale(1.1);
	}
	100% {
		transform: scale(1);
	}
}

.file-box {
	width: 90%;
	background-color: white;
	border-radius: 10px;
	padding: 15px;
	margin-bottom: 20px;
	box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.file-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 15px;
}

.file-duration {
	color: #666;
}

.action-box {
	display: flex;
	justify-content: space-between;
}

.action-btn {
	flex: 1;
	margin: 0 5px;
	height: 40px;
	line-height: 40px;
	font-size: 16px;
	background-color: #f1f1f1;
	color: #333;
}

.action-btn.primary {
	background-color: #2196f3;
	color: white;
}

.result-box {
	width: 90%;
	background-color: white;
	border-radius: 10px;
	padding: 15px;
	box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.result-title {
	font-size: 18px;
	font-weight: bold;
	margin-bottom: 10px;
	color: #333;
}

.result-content {
	color: #666;
	line-height: 1.5;
}
</style>
